package com.lcf.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.lcf.framework.exception.SysException;
import com.lcf.framework.vo.PageVO;
import com.lcf.system.dao.GoodsCategoryDao;
import com.lcf.system.dto.GoodsCategoryDTO;
import com.lcf.system.entity.GoodsCategory;
import com.lcf.system.query.GoodsCategoryPageQuery;
import com.lcf.system.service.GoodsCategoryService;
import com.lcf.system.vo.GoodsCategoryVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/**
 * 商品分类(GoodsCategory)表服务实现类
 *
 * @author lcf
 * @since 2025-05-02 11:55:00
 */
@Service("goodsCategoryService")
public class GoodsCategoryServiceImpl extends ServiceImpl<GoodsCategoryDao, GoodsCategory> implements GoodsCategoryService {

    @Override
    public boolean addGoodsCategory(GoodsCategoryDTO dto) {
        checkName(null, dto.getName());
        return BeanUtil.copyProperties(dto, GoodsCategory.class).insert();
    }

    @Override
    public boolean deleteGoodsCategory(long id) {
        return removeById(id);
    }

    @Override
    public boolean updateGoodsCategory(long id, GoodsCategoryDTO dto) {
        checkName(id, dto.getName());

        GoodsCategory goodsCategory = BeanUtil.copyProperties(dto, GoodsCategory.class);
        goodsCategory.setId(id);
        return goodsCategory.updateById();
    }

    @Override
    public GoodsCategoryVO getGoodsCategory(long id) {
        return BeanUtil.copyProperties(getById(id), GoodsCategoryVO.class);
    }

    @Override
    public PageVO<GoodsCategoryVO> getGoodsCategoryList(GoodsCategoryPageQuery query) {
        Page<GoodsCategory> page = Db.lambdaQuery(GoodsCategory.class)
                .like(StringUtils.isNotBlank(query.getName()), GoodsCategory::getName, query.getName())
                .page(query.toPage());

        return new PageVO<>(page, GoodsCategoryVO.class);
    }

    /**
     * 检查分类名称
     */
    public void checkName(Long id, String name) {
        GoodsCategory goodsCategory = Db.lambdaQuery(GoodsCategory.class)
                .ne(id != null, GoodsCategory::getId, id)
                .eq(GoodsCategory::getName, name).one();
        if (goodsCategory != null) {
            throw new SysException("分类名称已存在");
        }
    }
}

